<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Shop\Form;

use Laminas\Form\Form;
use User\Validator\UserPhoneExistsValidator;

class ChangeUserPhoneForm extends Form
{
    private $phoneArea;
    private $entityManager;
    private $userInfo;

    public function __construct(array $phoneArea, $entityManager, $userInfo, $name = 'change-user-phone-form', $options = [])
    {
        parent::__construct($name, $options);

        $this->setAttribute('method', 'post');

        $this->phoneArea    = $phoneArea;
        $this->entityManager= $entityManager;
        $this->userInfo     = $userInfo;

        $this->addElements();
        $this->addInputFilter();
    }

    protected function addElements()
    {
        if(count($this->phoneArea) == 1) {
            $this->add([
                'type'  => 'hidden',
                'name'  => 'areaCode',
                'attributes'=> [
                    'id'    => 'areaCode',
                    'value' => $this->phoneArea[0]['areaCode']
                ]
            ]);
        } else {
            $this->add([
                'type'  => 'select',
                'name'  => 'areaCode',
                'attributes'=> [
                    'id'    => 'areaCode',
                    'value' => $this->phoneArea['default']
                ],
                'options' => [
                    'value_options' => $this->phoneArea['list']
                ]
            ]);
        }

        $this->add([
            'type'  => 'text',
            'name'  => 'userPhone',
            'attributes' => [
                'id' => 'userPhone'
            ]
        ]);
    }

    protected function addInputFilter()
    {
        $inputFilter = $this->getInputFilter();

        $inputFilter->add([
            'name'      => 'areaCode',
            'required'  => true
        ]);

        $inputFilter->add([
            'name'      => 'userPhone',
            'required'  => true,
            'filters'   => [
                ['name' => 'StringTrim'],
                ['name' => 'StripTags']
            ],
            'validators'=> [
                [
                    'name' => UserPhoneExistsValidator::class,
                    'options'   => [
                        'entityManager' => $this->entityManager,
                        'userInfo'      => $this->userInfo
                    ]
                ]
            ]
        ]);
    }
}